"""
    TagRatePost

    @author: Jean-Lou Dupont
"""
import datetime
import logging
import os
import time

from google.appengine.ext import db

class TagRatePost(db.Expando):
    """ 
        FIELDS:
        =======
        user
        created
        modified
        url
        notes
        rating
    """
    user = db.UserProperty(required=True)
    created  = db.DateTimeProperty()
    modified = db.DateTimeProperty()
    
    @staticmethod
    def create( u, url = None ):

        now = datetime.datetime.now()        
        
        if url:
            p = TagRatePost.exists(u, url)
        else:      
            p = TagRatePost(user=u)
            p.created  = now
 
        p.modified = now
        
        return p
    
    @staticmethod
    def exists(u, url):
        """
            Verifies if USER u has already a post for URL url
            
            @return: TagRatePost instance IF found
        """
        query = db.Query( TagRatePost )

        query.filter('user = ', u   )
        query.filter('url = ',  url )
        try:
            result = query.fetch(limit=1)
        except:
            result = None
        
        if result:
            if ( len(result) == 1 ):
                return result[0]
        
        return None
    
    @staticmethod
    def defaultList( user, limite=10 ):
        query = db.Query( TagRatePost )
        
        try:
            query.filter('user = ', user)  # space is important!!
            query.order('-modified')
            result = query.fetch(limit=limite)    
        except Exception, e:
            logging.error( 'TagRatePost.defaultList: EXCEPTION raised, msg='+e.message )
            result = None
    
        return result
        
    @staticmethod
    def datedList( user, fromDate, limite=10 ):
        """
            @param fromdate: string 
        """
        reverse = False
        date = None
        if (fromDate is not None) and (fromDate is not ""):
            date = convertDate(fromDate)
        
        query = db.Query( TagRatePost )
        
        try:
            query.filter('user = ', user)  # space is important!!
            if (date is not None):
                logging.info("with date user[%s] fromDate[%s] date[%s]" % (user, fromDate, date))
                query.order('modified')
                query.filter('modified >=', date)
                reverse = True
            else:
                logging.info("WITHOUT date: user[%s]" % user)
                query.order('modified')
                reverse = True
            result = query.fetch(limit=limite)    
        except Exception, e:
            logging.error( 'TagRatePost.defaultList: EXCEPTION raised, msg='+e.message )
            result = (None, None)
    
        return (result, reverse)

    
def convertDate( date ):
    """ Converts a date in string format
        to a datastore compatible format
        
        Input format:   YYYY-MM-DD HH:MM:SS.ssssss
        Output format:  datetime
        
        @throws Exception
    """
    sdate = date.split('.')    
    try:
        return datetime.datetime.strptime(sdate[0], "%Y-%m-%d %H:%M:%S")
    except Exception,e:
        logging.error('exception whilst converting date[%s] msg[%s]' % (date,e))
        return None
    #
    #t = time.strptime('2008-10-29 18:00:08.866954', "%Y-%m-%d %H:%M:%S.")
